#include "PulseClient.h"
#include <QDebug>
#include <pulse/channelmap.h>
#include <pulse/context.h>
#include <pulse/def.h>
#include <pulse/introspect.h>
#include <pulse/mainloop.h>
#include <pulse/sample.h>
#include <pulse/stream.h>

struct Opdata {
    pa_operation* op;
    PulseClient* clt;
};

PulseClient::PulseClient()
{
    m_loop = pa_mainloop_new();
    m_api = pa_mainloop_get_api(m_loop);
    m_ctx = pa_context_new(m_api, "paclt");
    pa_context_set_state_callback(m_ctx, contextCallBack, this);
    pa_context_connect(m_ctx, nullptr, PA_CONTEXT_NOAUTOSPAWN, nullptr);
}

void PulseClient::contextCallBack(pa_context* ctx, void* data)
{
}

void PulseClient::setSpeakerVolume(QString name, int vol)
{
    pa_cvolume volume;
    pa_context_set_sink_volume_by_name(
        m_ctx, name.toStdString().c_str(), &volume,
        [](pa_context* c, int success, void* data) {
            qDebug() << "setdefault sink volume: " << success;
        },
        this);
}

void PulseClient::setInputVolume(QString name, int vol)
{
    pa_cvolume volume;
    pa_context_set_source_volume_by_name(
        m_ctx, name.toStdString().c_str(), &volume,
        [](pa_context* c, int success, void* data) {
            qDebug() << "setdefault source volume: " << success;
        },
        this);
}

void PulseClient::setDefaultSpeaker(QString name)
{
    pa_context_set_default_sink(
        m_ctx, name.toStdString().c_str(),
        [](pa_context* c, int success, void* data) {
            qDebug() << "setdefault sink: " << success;
        },
        this);
}

void PulseClient::setDefaultMicphone(QString name)
{
    pa_context_set_default_source(
        m_ctx, name.toStdString().c_str(),
        [](pa_context* c, int success, void* data) {
            qDebug() << "setdefault source: " << success;
        },
        this);
}

void PulseClient::startPlayBack()
{
    pa_sample_spec ss = {
        .rate = 44100,
        .format = PA_SAMPLE_S16LE,
        .channels = 1
    };

    pa_channel_map map = {
        .channels = 1,
        .map = {}
    };

    pa_stream* pcm = pa_stream_new(m_ctx, "", &ss, &map);
}
